#include "music.h"
#include<QUuid>
#include<QMediaPlayer>
#include<QDebug>
#include<QCoreApplication>
#include<QSqlQuery>
#include<QSqlError>

Music::Music()
    :isLike(false)
    ,isHistory(false)
{

}

Music::Music(QUrl url)
    :musicUrl(url)
    ,isLike(false)
    ,isHistory(false)

{
    musicId=QUuid::createUuid().toString();
    parseMediaMetaDate();
}

void Music::setMusicId(const QString &musicId)
{
    this->musicId=musicId;
}
void Music::setMusicName(const QString& musicName)
{
    this->musicName=musicName;
}
void Music::setMusicSinger(const QString& musicSinger)
{
    this->musicSinger=musicSinger;
}
void Music::setMusicAlbum(const QString& musicAlbum)
{
    this->musicAlbum=musicAlbum;
}
void Music::setDuration(qint64 durable)
{
    this->duration=durable;
}

void Music::setMusicUrl(const QString &musicUrl)
{
    this->musicUrl=musicUrl;
}
void Music::setIsLike(bool isLike)
{
    this->isLike=isLike;
}
void Music::setIsHistory(bool isHistory)
{
    this->isHistory=isHistory;
}

QString Music::getMusicName()const
{
    return this->musicName;
}
QString Music::getMusicSinger()const
{
    return this->musicSinger;
}
QString Music::getMusicAlbum()const
{
    return this->musicAlbum;
}
qint64 Music::getDuration()const
{
    return this->duration;
}
bool Music::getIsLike()const
{
    return this->isLike;
}
bool Music::getIsHistory()const
{
    return this->isHistory;
}

QUrl Music::getMusicUrl()const
{
    return this->musicUrl;
}

QString Music::getMusicId() const
{
    return this->musicId;
}

QString Music::getLrcFilePath() const
{
    QString lrcPath=musicUrl.toLocalFile();
    lrcPath.replace(".mp3",".lrc");
    lrcPath.replace(".flac",".lrc");
    lrcPath.replace(".mpga",".lrc");
    return lrcPath;
}

void Music::writeMusicToDB()
{
    QSqlQuery query;
    query.prepare("select exists(select 1 from musicInfo where musicId= ?)");
    query.addBindValue(musicId);
    if(!query.exec())
    {
        qDebug()<<"查询失败"<<query.lastError().text();
        return;
    }

    if(query.next())
    {
        bool isExists=query.value(0).toBool();
        if(isExists)
        {
            query.prepare("update musicInfo set isLike=?,isHistory=? where musicId=?");
            query.addBindValue(isLike?1:0);
            query.addBindValue(isHistory?1:0);
            query.addBindValue(musicId);
            if(!query.exec())
            {
                qDebug()<<"更新结果失败"<<query.lastError().text();
                return;
            }
            qDebug()<<"更新结果成功";
        }
        else
        {
            query.prepare("insert into musicInfo(musicId, musicName, musicSinger, albumName, duration, musicUrl, isLike, isHistory) values(?,?,?,?,?,?,?,?)");
            query.addBindValue(musicId);
            query.addBindValue(musicName);
            query.addBindValue(musicSinger);
            query.addBindValue(musicAlbum);
            query.addBindValue(duration);
            query.addBindValue(musicUrl.toLocalFile());
            query.addBindValue(isLike?1:0);
            query.addBindValue(isHistory?1:0);
            if(!query.exec())
            {
                qDebug()<<"插入失败"<<query.lastError().text();
                return;
            }
            qDebug()<<"插⼊music信息: "<<musicName<<" "<<musicId;
        }
    }
}

void Music::parseMediaMetaDate()
{
    QMediaPlayer player;
    player.setMedia(musicUrl);//立马返回
    // 媒体元数据解析需要时间，只有等待解析完成之后，才能提取⾳乐信息，此处循环等待
    // 循环等待时：主界⾯消息循环就⽆法处理了，因此需要在等待解析期间，让消息循环继续处理
    while(!player.isMetaDataAvailable())//死循环---这里阻塞了Qt框架被阻塞
    {
        QCoreApplication::processEvents();
    }
    if(player.isMetaDataAvailable())
    {
        musicName=player.metaData("Title").toString();
        musicSinger=player.metaData("Author").toString();
        musicAlbum=player.metaData("AlbumTitle").toString();
        duration=player.metaData("Duration").toLongLong();

        QString fileNmae=musicUrl.fileName();
        int index=fileNmae.indexOf('-');
        if(musicName.isEmpty())
        {
            if(index!=-1)
            {
                musicName=fileNmae.mid(0,index).trimmed();
            }
            else
            {
                musicName=fileNmae.mid(0,fileNmae.indexOf('.')).trimmed();
            }
        }

        if(musicSinger.isEmpty())
        {
            if(index!=-1)
            {
                musicSinger=fileNmae.mid(index+1,fileNmae.indexOf('.')-index-1).trimmed();
            }
            else
            {
                musicSinger="未知歌手";
            }
        }

        if(musicAlbum.isEmpty())
        {
            musicAlbum="未知专辑";
        }

        qDebug()<<musicName<<":"<<musicSinger<<":"<<musicAlbum<<":"<<duration;
    }
}
